#include "command.h"

static void sha1(char *name, char *offset1){
    char arr[1024] = { 0 };
    sprintf(arr, "sha1sum %s", name);
    char buf[1024];
    FILE *pipe = popen(arr, "r");

    fread(buf,1, sizeof(buf), pipe);
    strncpy(offset1, buf, 40);

    pclose(pipe);
}

void command_puts(int netFD, sendc_t *sc){
    printf("33333333\n");
    char buf[41] = { 0 };
    sha1(sc->path, buf);
    send(netFD, buf, strlen(buf), MSG_NOSIGNAL);

    int reply_num;
    recv(netFD, &reply_num, sizeof(int), MSG_WAITALL);
    if(reply_num == 1){
        printf("急速秒传完成\n");
        return;
    }

    char offset[128] = { 0 };
    recv(netFD, offset, sizeof(offset), MSG_WAITALL);

    //计算偏移值
    off_t flag = atoi(offset) - atoi(offset)%4096;

    printf("22222222\n");
    int fd = open(sc->path, O_RDONLY);
    struct stat fl;
    fstat(fd, &fl);

    size_t file_size = fl.st_size - flag;
    send(netFD, &file_size, sizeof(size_t), MSG_NOSIGNAL);

    sendfile(netFD, fd, &flag, file_size);
    close(fd);

}
